package com.yanfan.zutai.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.yanfan.common.annotation.Log;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.page.TableDataInfo;
import com.yanfan.common.enums.BusinessType;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.common.utils.poi.ExcelUtil;
import com.yanfan.zutai.config.TaosConnectTool;
import com.yanfan.zutai.domain.BDeviceHistory;
import com.yanfan.zutai.domain.BDeviceHistoryData;
import com.yanfan.zutai.domain.BDeviceRealData;
import com.yanfan.zutai.domain.BDeviceZtBind;
import com.yanfan.zutai.domain.vo.BDeviceRealDataZt;
import com.yanfan.zutai.service.IBDeviceHistoryService;
import com.yanfan.zutai.service.IBDeviceRealDataService;
import com.yanfan.zutai.util.Detect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 设备历史记录Controller
 *
 * @author ruoyi
 * @date 2021-02-27
 */
@RestController
@RequestMapping("/zutai/bDeviceHistory")
public class BDeviceHistoryController extends BaseController {
    @Autowired
    private IBDeviceHistoryService bDeviceHistoryService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private IBDeviceRealDataService bDeviceRealDataService;

    /**
     * 查询设备历史记录列表
     */
    @GetMapping("/list")
    //@SysQueryData
    public TableDataInfo list(BDeviceHistory bDeviceHistory) {
        startPage();
        List<BDeviceHistory> list = bDeviceHistoryService.selectBDeviceHistoryList(bDeviceHistory);
        for (int i = 0; i < list.size(); i++) {
            BDeviceHistory deviceHistory = list.get(i);
            List<BDeviceRealData> bDeviceRealDataList = new ArrayList<>();
            if (Detect.notEmpty(deviceHistory.getDeviceData())) {
                Map map = JSON.parseObject(deviceHistory.getDeviceData(), Map.class);
                for (Object key : map.keySet()) {
                    BDeviceRealData bDeviceRealData = new BDeviceRealData();
                    bDeviceRealData.setParamName(key.toString());
                    bDeviceRealData.setParamValue(map.get(key).toString());
                    bDeviceRealDataList.add(bDeviceRealData);
                }
            }
            deviceHistory.setBDeviceRealDataList(bDeviceRealDataList);
        }
        return getDataTable(list);
    }

    /**
     * 导出设备历史记录列表
     */
    @Log(title = "设备历史记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BDeviceHistory bDeviceHistory) {
        startPage();
        List<BDeviceHistory> list = bDeviceHistoryService.selectBDeviceHistoryList(bDeviceHistory);
        ExcelUtil<BDeviceHistory> util = new ExcelUtil<BDeviceHistory>(BDeviceHistory.class);
        util.exportExcel(response, list, "历史报表");
    }

    /**
     * 获取设备历史记录详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(bDeviceHistoryService.selectBDeviceHistoryById(id));
    }

    /**
     * 新增设备历史记录
     */
    @Log(title = "设备历史记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BDeviceHistory bDeviceHistory) {
        return toAjax(bDeviceHistoryService.insertBDeviceHistory(bDeviceHistory));
    }

    /**
     * 修改设备历史记录
     */
    @Log(title = "设备历史记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BDeviceHistory bDeviceHistory) {
        return toAjax(bDeviceHistoryService.updateBDeviceHistory(bDeviceHistory));
    }

    /**
     * 删除设备历史记录
     */
    @Log(title = "设备历史记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        BDeviceHistory bDeviceHistoryQuery = new BDeviceHistory();
        List<Long> idList = new ArrayList<>();
        Collections.addAll(idList, ids);
        bDeviceHistoryQuery.setIdList(idList);
        List<BDeviceHistory> bDeviceHistories = bDeviceHistoryService.selectBDeviceHistoryList(bDeviceHistoryQuery);
        Boolean isAuth = true;
        for (int i = 0; i < bDeviceHistories.size(); i++) {
            BDeviceHistory bDeviceHistory = bDeviceHistories.get(i);
            if (bDeviceHistory.getDeptIdStrs() != null && bDeviceHistory
                    .getDeptIdStrs()
                    .indexOf(SecurityUtils.getDeptId().toString()) == -1) {
                isAuth = false;
                System.out.println("无权限删除数据");
            }
        }
        if (!isAuth && !SecurityUtils.getUsername().equals("admin")) {
            return AjaxResult.error("无权限删除数据");
        }
        return toAjax(bDeviceHistoryService.deleteBDeviceHistoryByIds(ids));
    }

    /**
     * 查询设备实时数据列表
     */
    @GetMapping("/getRealDataList")
    public AjaxResult getRealDataList(BDeviceRealDataZt bDeviceRealDataZt) {
        BeanPropertyRowMapper rowMapper = new BeanPropertyRowMapper<>(BDeviceHistoryData.class);
        if (Detect.isEmpty(bDeviceRealDataZt.getHeadListStr())) {
            return AjaxResult.error("无数据信息");
        }
        String[] paramNameList = bDeviceRealDataZt.getHeadListStr().split(";");
        List<String> imeiList = new ArrayList<>();
        if (Detect.notEmpty(bDeviceRealDataZt.getZtGuid())) {
            String ztSql = "select * from b_device_zt_bind where zt_guid=?";
            BeanPropertyRowMapper<BDeviceZtBind> bindBeanPropertyRowMapper = new BeanPropertyRowMapper<>(BDeviceZtBind.class);
            List<BDeviceZtBind> ztBinds = jdbcTemplate.query(ztSql, bindBeanPropertyRowMapper, bDeviceRealDataZt.getZtGuid());
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < ztBinds.size(); i++) {
                stringBuffer.append("'");
                stringBuffer.append(ztBinds.get(i).getDeviceMac());
                stringBuffer.append("'");
                stringBuffer.append(",");
            }
            bDeviceRealDataZt.setDeviceImei(stringBuffer.substring(0, stringBuffer.toString().length() - 1));
            for (int i = 0; i < ztBinds.size(); i++) {
                imeiList.add(ztBinds.get(i).getDeviceMac());
            }
        }
        StringBuffer paramBuffer = new StringBuffer();
        for (int i = 0; i < paramNameList.length; i++) {
            paramBuffer.append("'");
            paramBuffer.append(paramNameList[i]);
            paramBuffer.append("'");
            paramBuffer.append(",");
        }
        bDeviceRealDataZt.setHeadListStr(paramBuffer.substring(0, paramBuffer.toString().length() - 1));
        Integer limit = 60 * paramNameList.length;
        String sql = "select * from b_device_history_data where  device_imei in({}) and  param_name in({}) order by report_time desc limit " + limit;
        String format = StrUtil.format(sql, bDeviceRealDataZt.getDeviceImei(), bDeviceRealDataZt.getHeadListStr());
        JdbcTemplate jdbcTaosTemplate = TaosConnectTool.getInstance().getJdbcTemplate();
        List<BDeviceHistoryData> list = jdbcTaosTemplate.query(format, rowMapper);
        return AjaxResult.success("实时数据", list);
    }
}
